﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Win32;
using System.Configuration;
namespace KTX.Vinh
{
    /// <summary>
    /// Config database connection
    /// </summary>
    public partial class FrmConfig : Form
    {
        #region Properties
        private SqlConnection conn;
        private string user = "";
        private string pass = "";
        private string server = "";
        private string database = "";
        public const string strSqlServerAuthentication = "Data Source={0};Initial Catalog={1};User Id={2};Password={3};";
        public const string strWindowsAuthentication = "Data Source={0};Initial Catalog={1};Integrated Security=true;";

        #endregion

        public FrmConfig()
        {
            InitializeComponent();
        }
        
        #region Methods

        /// <summary>
        ///  Return Connection String
        /// </summary>
        /// <returns></returns>
        public void ChangeTextBox(bool bol = true)
        {

            txtLogin.Enabled = bol;
            txtPassword.Enabled = bol;
        }
        public string StrConn(){
            server = lstLocal.SelectedItem.ToString();
            user = txtLogin.Text;
            pass = txtPassword.Text;
            database = cbbDatabase.Text;
            string str;
            if (rdUseWindowsAuthentication.Checked)
                str = string.Format(strWindowsAuthentication, server, database);
            else
                str = string.Format(strSqlServerAuthentication, server, database, user, pass);

            return str;

        }
        #endregion
        /// <summary>
        /// Get Local Instances
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region Events
        private void FrmConfig_Load(object sender, EventArgs e)
        {
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
            var instances = (String[])rk.GetValue("InstalledInstances");// Implicitly Typed Array in C# 3.0
            if (instances.Length > 0)
            {
                foreach (String element in instances)
                {
                    if (element.Equals("MSSQLSERVER"))
                    {
                        lstLocal.Items.Add(System.Environment.MachineName);
                    }
                    else
                    {
                        lstLocal.Items.Add(System.Environment.MachineName + @"\" + element);
                    }
                }
            }
        }
        private void rdUseWindowsAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            cbbDatabase.Items.Clear();
            cbbDatabase.Enabled = false;
            ChangeTextBox(false);
        }
        private void rdUseSqlserverAuthentication_CheckedChanged(object sender, EventArgs e)
        {
            cbbDatabase.Items.Clear();
            cbbDatabase.Enabled = false;
            ChangeTextBox();
        }
        
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            string str;
            try
            {
                if (rdUseWindowsAuthentication.Checked)
                {
                    str = string.Format(strWindowsAuthentication, lstLocal.SelectedItem.ToString(), "master");
                    conn = new SqlConnection(str);
                    conn.Open();
                    MessageBox.Show("Kết nối thành công", "Succeed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbbDatabase.Enabled = true;
                }
                else
                {
                    str = string.Format(strSqlServerAuthentication, lstLocal.SelectedItem.ToString(), "master", txtLogin.Text, txtPassword.Text);
                    conn = new SqlConnection(str);
                    conn.Open();
                    MessageBox.Show("Kết nối thành công", "Succeed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cbbDatabase.Enabled = true;
                }
                // procedure show database list
                var cmd = new SqlCommand("SP_DATABASES", conn);
                var reader = cmd.ExecuteReader();
                while(reader.Read())
                {
                    cbbDatabase.Items.Add(reader[0].ToString());
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            try{
            
                MessageBox.Show(StrConn());
                Configuration _config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
                _config.ConnectionStrings.ConnectionStrings[1].ConnectionString = StrConn();
                _config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(_config.ConnectionStrings.SectionInformation.Name);
                Properties.Settings.Default.Reload();
                MessageBox.Show("Đã lưu cấu hình!" + Environment.NewLine + "Vui lòng khởi động lại chương trình!");
                Close();
                Application.Exit();
            }
            catch (Exception ex)
            {
                string s = String.Format("{0};{1}", "Không tìm thấy file cấu hình!", ex.Message);
                string t = String.Format("{0};{1}", "Lỗi", "Error");
                MessageBox.Show(s, t);
            }
        }
        #endregion
    }
}
